package com.lzx.hbh_system.service.zffyxxgl.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzx.hbh_system.bo.filter.zffyxxgl.PayOrderInfoFilter;
import com.lzx.hbh_system.bo.zffyxxgl.PayInfo;
import com.lzx.hbh_system.bo.zffyxxgl.PayInfoDetail;
import com.lzx.hbh_system.bo.zffyxxgl.PayOrderInfo;
import com.lzx.hbh_system.dto.zffyxxgl.PayOrderInfoDto;
import com.lzx.hbh_system.mapper.zffyxxgl.PayInfoDetailMapper;
import com.lzx.hbh_system.mapper.zffyxxgl.PayInfoMapper;
import com.lzx.hbh_system.mapper.zffyxxgl.PayOrderInfoMapper;
import com.lzx.hbh_system.service.zffyxxgl.PayOrderInfoService;
import com.lzx.hbh_system.util.SnowFlakeUtil;
import com.lzx.hbh_system.util.TurnDateToStringUtil;
import com.lzx.hbh_system.util.responseEntity.RespOutMsgHeader;
import com.lzx.hbh_system.util.responseEntity.ResponseView;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
public class PayOrderInfoServiceImpl extends ServiceImpl<PayOrderInfoMapper, PayOrderInfo> implements PayOrderInfoService {
    @Autowired
    private PayOrderInfoMapper payOrderInfoMapper;
    @Autowired
    private PayInfoMapper payInfoMapper;
    @Autowired
    private PayInfoDetailMapper payInfoDetailMapper;
    @Autowired
    private ModelMapper modelMapper;

    @Override
    public ResponseView queryAllPayOrderInfoPageFilter(PayOrderInfoFilter filter) {
        // 初始化返回视图
        // 校验参数
        ResponseView responseView = checkParams("00",filter);
        if(responseView.getRespOutMsgHeader().getRespCode().equals(500)){
            return responseView;
        }
        // 逻辑实现
        // 初始化分页对象
        Page<PayOrderInfoDto> payInfoOrderDtoPage = new Page<>(filter.getPageIndex(),filter.getPageSize());
        // 查询
        IPage<PayOrderInfoDto> payOrderInfoDtoIPage = payOrderInfoMapper.selectAllPayOrderInfoPageFilter(payInfoOrderDtoPage,filter);
        // 处理结果集
        List<PayOrderInfoDto> payOrderInfoDtos = verifyAllReconciliationFlag(payOrderInfoDtoIPage.getRecords()); // 校验是否存在未对账信息 并返回处理完的列表
        // 返回响应消息
        responseView.setRespOutMsgHeader(RespOutMsgHeader.success(payOrderInfoDtos.size(),"查询成功！"));
        // 设置返回结果
        Map<String,Object> map = new HashMap<>();
        map.put("dataArray", payOrderInfoDtos.toArray());
        map.put("currentPage",payOrderInfoDtoIPage.getCurrent());
        map.put("totalsData",payOrderInfoDtoIPage.getTotal());
        responseView.setMain(map);
        return responseView;
    }

    @Override
    public ResponseView addOnePayOrderInfo(PayOrderInfoFilter filter) {
        // 初始化返回视图
        // 校验参数
        ResponseView responseView = checkParams("03",filter);
        if(responseView.getRespOutMsgHeader().getRespCode().equals(500)){
            return responseView;
        }
        // 逻辑实现
        // 判断是否存在相同住户的收款单
        QueryWrapper<PayOrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("household_code",filter.getPayOrderInfo().getHouseholdCode());
        PayOrderInfo OriginpayOrderInfo = payOrderInfoMapper.selectOne(queryWrapper);
        if (OriginpayOrderInfo != null){
            // 存在
            // 叠加总金额-修改
            BigDecimal oringPayAmount = OriginpayOrderInfo.getOrderPayAmount() ; // 获取原总金额
            BigDecimal newPayAmount = oringPayAmount.add(filter.getPayOrderInfo().getOrderPayAmount()); // 叠加
            PayOrderInfo payOrderInfonew = new PayOrderInfo();
            modelMapper.map(OriginpayOrderInfo,payOrderInfonew);
            payOrderInfonew.setOrderTime(TurnDateToStringUtil.getTime()); // 设置收款时间
            payOrderInfonew.setOrderPayAmount(newPayAmount); // 设置总收款金额
            // 保存数据
            payOrderInfoMapper.updateById(payOrderInfonew);
            // 返回响应消息
            responseView.setRespOutMsgHeader(RespOutMsgHeader.success("操作成功！"));
            return responseView;
        }
        PayOrderInfo payOrderInfo = filter.getPayOrderInfo();
        String key = SnowFlakeUtil.getId(); // 生成雪花主键
        payOrderInfo.setId(key); // 设置主键
        payOrderInfo.setValiFlag("1"); // 设置默认有效
        payOrderInfo.setOrderTime(TurnDateToStringUtil.getTime()); // 设置付款时间

        // 保存数据
        payOrderInfoMapper.insert(payOrderInfo);
        // 返回响应消息
        responseView.setRespOutMsgHeader(RespOutMsgHeader.success("操作成功！"));
        return responseView;
    }

    @Override
    public ResponseView modifyBatchPayOrderInfo(PayOrderInfoFilter filter) {
        // 初始化返回视图
        // 校验参数
        ResponseView responseView = checkParams("03",filter);
        if(responseView.getRespOutMsgHeader().getRespCode().equals(500)){
            return responseView;
        }
        // 逻辑实现
        List<PayOrderInfo> payOrderInfos = filter.getPayOrderInfos();
        payOrderInfos.forEach(item -> {
            if (Objects.equals(filter.getSfzf(), "1")){
                item.setValiFlag("0"); // 设置数据失效 作废数据
            }
            payOrderInfoMapper.updateById(item);
        });
        // 返回响应消息
        responseView.setRespOutMsgHeader(RespOutMsgHeader.success("操作成功！"));
        return responseView;
    }

    /**
     * 判断列表的账单对应的住户的支付信息是否存在未对账信息，若是则设置账单存在未对账状态 ，否则 已对账
     * @param OriginpayOrderInfoDtos
     * @return
     */
    public List<PayOrderInfoDto> verifyAllReconciliationFlag(List<PayOrderInfoDto> OriginpayOrderInfoDtos){
        List<PayOrderInfoDto> newPayOrderInfoDtoList = new ArrayList<>();
        OriginpayOrderInfoDtos.forEach(item -> {
            // 查询对应住户的费用项目是否存在未对账
            QueryWrapper<PayInfo> PayInfoqueryWrapper = new QueryWrapper<>();
            PayInfoqueryWrapper.eq("household_code",item.getHouseholdCode());
            List<PayInfo> payInfos = payInfoMapper.selectList(PayInfoqueryWrapper);
            List<PayInfoDetail> NopayReconciliation_PayInfoDetail = new ArrayList<>();
            payInfos.forEach(payinfo -> {
                QueryWrapper<PayInfoDetail> PayInfoDetailqueryWrapper = new QueryWrapper<>();
                PayInfoDetailqueryWrapper.eq("pay_info_code",payinfo.getId());
                PayInfoDetail payInfoDetail = payInfoDetailMapper.selectOne(PayInfoDetailqueryWrapper);
                if(payInfoDetail.getReconciliationFlag().equals("2")){
                    NopayReconciliation_PayInfoDetail.add(payInfoDetail);
                }
            });
            if (NopayReconciliation_PayInfoDetail.size()!=0){
                // 未对账列表不为空
                // 存在未对账的支付详情 就 说明 未完全对账 设置 '2'
                item.setHasAllReconciliationFlag("2");
            }else{
                // 未对账列表为空
                // 说明该住户支付信息详情已经全部对账 设置 ’1‘
                item.setHasAllReconciliationFlag("1");
            }
            newPayOrderInfoDtoList.add(item);
        });
        return newPayOrderInfoDtoList;
    }
    /**
     * 参数校验函数
     *  01 删除
     *  02 修改
     *  03 新增
     *  00 查询
     * @param filter
     * @return
     */
    public ResponseView checkParams(String operaType, PayOrderInfoFilter filter){
        // 初始化返回视图
        ResponseView responseView = new ResponseView();
         if (Objects.equals(operaType, "02")){
            if (filter.getPayOrderInfos().size() == 0){
                responseView.setRespOutMsgHeader(RespOutMsgHeader.error("修改的账单信息至少选择一种！"));
                return responseView;
            }
        }
        responseView.setRespOutMsgHeader(RespOutMsgHeader.success());
        return responseView;
    }
}
